<template>
    <div class="container-fluid">
        <div class="row page-title">
            <div class="col-xs-11">
                <h1>场馆管理</h1>
            </div>
            <div class="col-xs-1">
                <a title="添加" @click="add('')">
                    <el-tooltip content="添加" placement="top">
                        <i class="el-icon-plus"></i>
                    </el-tooltip>
                </a>
            </div>
        </div>
        <el-row>
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="场馆名称">
                    <el-input clearable v-model="searchForm.gymName"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row>
            <el-col :span="24" class="table-bottom-margin">
                <el-table v-loading="loading" :data="tableData" border style="width: 100%" :header-cell-class-name="headerbg">
                    <!-- <el-table-column prop="gymId" label="场馆编号"> </el-table-column> -->
                    <el-table-column prop="gymName" label="场馆名称"></el-table-column>
                    <el-table-column prop="gymLocation" label="场馆地址"></el-table-column>
                    <el-table-column prop="gymTelephone" label="场馆电话"></el-table-column>
                    <el-table-column prop="gymServerAddress" label="服务地址IP"></el-table-column>
                    <el-table-column prop="gymExpireTime" label="系统过期时间"></el-table-column>
                    <el-table-column prop="gymDesc" label="描述信息"></el-table-column>
                    <el-table-column label="是否有效"><span slot-scope="scope">{{scope.row.valid?'是':'否'}}</span></el-table-column>
                    <el-table-column prop="creationTime" label="创建时间"></el-table-column>
                    <el-table-column prop="lastModifiedTime" label="修改时间"></el-table-column>
                    <el-table-column label="操作" align="center" min-width="70">
                        <template slot-scope="scope">
                            <el-tooltip content="功能同步与绑定" placement="top">
                                <i class="fa fa-link el-text-yellow" @click="view(scope.row)"></i>
                            </el-tooltip>
                            <el-tooltip content="编辑" placement="top">
                                <i class="fa fa-edit el-text-blue" @click="edit(scope.row.gymId)"></i>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <i class="fa fa-trash el-text-danger" @click="del(scope.row.gymId)"></i>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>    
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24" class="table-bottom-margin" style="text-align:right">
                <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange" :current-page="currentPage"
                    :page-sizes="[10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="count">
                </el-pagination>
            </el-col>   
        </el-row>  
        <!--添加/编辑-->
        <el-dialog title="场馆管理" :visible.sync="dialogFormVisible">
            <el-form :model="form" ref="form" :rules="rules" label-width="25%">
                
                <el-form-item label="场馆名称：" prop="gymName">
                    <el-input v-model.trim="form.gymName" placeholder="请输入场馆名称" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="场馆地址：" prop="gymLocation">
                    <el-input v-model.trim="form.gymLocation" placeholder="请输入场馆地址" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="场馆电话：" prop="gymTelephone">
                    <el-input v-model.trim="form.gymTelephone" placeholder="请输入场馆电话" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="服务地址IP：" prop="gymServerAddress">
                    <el-input v-model.trim="form.gymServerAddress" placeholder="请输入服务地址IP" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="系统过期时间" prop="gymExpireTime">
                    <el-date-picker clearable
                        v-model="form.gymExpireTime"
                        type="datetime"
                        style="width:60%;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="描述信息：" prop="gymDesc">
                    <el-input type="textarea" :rows="2" v-model.trim="form.gymDesc" placeholder="请输入描述信息" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="是否有效：" prop="valid">
                    <el-radio-group v-model="form.valid">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" size="medium">确 定</el-button>
                <el-button @click="dialogFormVisible = false" size="medium">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 场馆功能 -->
        <el-dialog :title="'功能绑定与同步 - '+formView.gymName" :visible.sync="dialogViewVisible">
            <el-form :model="formView" ref="formView" label-width="0">
                
                <el-form-item label="" prop="isSync" label-width="21px">
                    <el-checkbox v-model="formView.isSync">是否同步</el-checkbox>
                </el-form-item>
                <el-form-item label="" prop="gymLocation">
                    <el-tree :data="viewTreeList" node-key="viewId" ref="tree" :default-expanded-keys="[1,2]" :props="defaultProps" show-checkbox>
                    </el-tree>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveView" size="medium">确 定</el-button>
                <el-button @click="dialogViewVisible = false" size="medium">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data(){
            return{
                currentPage:1,
                pageSize:10,
                count:0,
                headerbg:'headerbg',//表格头部背景色
                tableData:[],
                rules:{
                    gymName:[
                        { required: true, min: 1, max:10, message: '长度在 1 到 10 个字符' },
                    ],
                    gymLocation:[
                        { required: false, max:100, message: '长度不能超过 100 个字符' },
                    ],
                    gymTelephone:[
                        { required: false, message: '请输入场馆电话', trigger: 'blur' },
                    ],
                    gymServerAddress:[
                        { required: false, max:100, message: '长度不能超过 100 个字符' }
                    ],
                    gymExpireTime:[
                        { required: true, message: '请选择系统过期时间', trigger: 'change' }
                    ],
                    gymDesc:[
                        { required: false, max:100, message: '长度不能超过 100 个字符' },
                    ]
                },
                searchForm:{
                    gymName:''
                },
                dialogFormVisible:false,
                form:{},
                formView:{
                    isSync:true
                },
                dialogViewVisible: false,
                viewTreeList:[],
                defaultProps: {
                    children: 'children',
                    label: 'viewName'
                },
                viewSaveType: 0,//0添加1编辑
                loading:true,
                check:true
            }
        },
        components: {
        },
        created() {
            axios.get(`view/getTree?type=`,{
            })
            .then( (res)=> {
                this.viewList = res.data;
                this.viewTreeList = toTree(res.data);
            })
            .catch( (error)=> {
                this.viewTreeList = [];
                this.$notify.error({title: '错误',message:error||'获取表格列表失败！'});
            });
            function toTree(data) {
                var parentIdData = [];
                data.forEach(function (item) {
                    parentIdData.push(item.parentId||'');
                    delete item.children;
                });
                var val = [{ viewName:'前台功能',viewId:1,children:[] },{ viewName:'后台功能',viewId:2,children:[] }];
                data.forEach(function (item,index) {
                    var parent = data.find(t=>t.viewId==item.parentId);
                    if (parent) {
                        (parent.children || ( parent.children = [] )).push(item);
                        if(typeof parent.lastIndex!=='number'){
                            parent.lastIndex = parentIdData.lastIndexOf(item.parentId);
                        }
                        if(index==parent.lastIndex){
                            parent.children = parent.children.sort((a,b)=>a.sort-b.sort);
                        }
                    } else {
                        // val[item.type].children.push(item);
                        val[item.type].children[item.sort] = item;
                    }
                });
                val[0].children = val[0].children.filter(t=>!!t);
                val[1].children = val[1].children.filter(t=>!!t);
                return val.filter(t=>t.children.length>0);
            }
        },
        mounted() {
            this.getList(10,this.currentPage);
        },
        methods:{
            search:function(){
                this.getList(10,this.currentPage);
            },
            getList:function(PageSize,PageIndex){
                this.loading = true;
                axios.get(`gym/list?pageSize=${PageSize}&page=${PageIndex}&gymName=${this.searchForm.gymName}`,{
                })
                .then( (res)=> {
                    this.count = res.total;
                    this.tableData = res.data.map(t=>{
                        t.gymExpireTime = t.gymExpireTime?moment(t.gymExpireTime).format("YYYY-MM-DD HH:mm:ss"):'';
                        t.creationTime = moment(t.creationTime).format("YYYY-MM-DD HH:mm:ss");
                        t.lastModifiedTime = moment(t.lastModifiedTime).format("YYYY-MM-DD HH:mm:ss");
                        return t;
                    });
                    this.loading = false;
                })
                .catch( (error)=> {
                    this.count = 0;
                    this.tableData = [];
                    this.$notify.error({title: '错误',message:error||'获取表格列表失败！' });
                });
            },
            view(row){//打开功能弹框
                axios.get(`view/getGymViews?gymId=${row.gymId}`,{
                })
                .then( (res)=> {
                    this.viewSaveType = 1;
                    var parentIdArr = this.viewList.map(t=>t.parentId);
                    var selectedChildViews = res.data[0].viewIds.split(',').filter(t=>!parentIdArr.includes(t));
                    this.$refs.tree.setCheckedKeys(selectedChildViews);
                })
                .catch( (error)=> {
                    this.viewSaveType = 0;
                    this.$refs.tree.setCheckedKeys([]);
                    // this.$notify.error({title: '错误',message:error||'获取功能列表失败！'});
                });
                this.dialogViewVisible = true;
                this.formView.gymId = row.gymId;
                this.formView.gymName = row.gymName;
                this.formView.isSync = true;//同步
            },
            saveView(){//保存场馆与功能的绑定
                var selectedViews = this.$refs.tree.getCheckedNodes(false,true);
                if(selectedViews.length==0){
                    this.$notify({title: '警告',message: '请勾选功能',type: 'warning',duration:1200});
                    return;
                }
                this.formView.viewIds = selectedViews.map(t=>t.viewId).filter(t=>t.length>1).join();
                axios.post(`sync/view`,this.formView,{}).then((res)=>{
                    this.dialogViewVisible = false;
                    this.$notify({title: '成功',message: (this.formView.isSync?'同步':'绑定')+'场馆功能成功！',type: 'success'});
                }).catch((error)=>{
                    this.$notify.error({title: '错误',message:error||(this.formView.isSync?'同步':'绑定')+'失败！'});
                })
            },
            del:function(id){
                this.$confirm('确定需要删除该场馆?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`gym/remove?gymId=${id}`,{},{
                    }).then((res)=>{
                        this.getList(10,this.currentPage);
                        this.$notify({title: '成功',message: '删除成功！',type: 'success'});
                    }).catch( (error)=> {
                        this.$notify.error({title: '错误',message:error||'删除失败！'});
                    });
                },()=>{})
            },
            add(){
                this.dialogFormVisible = true;
                this.form = {
                    gymName:'',
                    gymLocation:'',
                    gymTelephone:'',
                    gymServerAddress:'',
                    gymExpireTime:null,
                    gymDesc:'',
                    valid: true
                };
                this.$nextTick(() => {
                    this.$refs.form.clearValidate();
                });
            },
            edit(id){
                this.dialogFormVisible = true;
                axios.get(`gym/select?gymId=${id}`,{},{
                }).then((res)=>{
                    var {lastModifiedTime,creationTime,...arr} = res.data;
                    arr.gymExpireTime = arr.gymExpireTime?moment(arr.gymExpireTime):'';
                    this.form = arr;
                }).catch( (error)=> {
                });
            },
            save(){
                var errorInfo = this.validateFun();
                if(errorInfo){
                    this.$notify({title: '警告', message: errorInfo, type: 'warning',duration:1200});
                    return;
                }
                axios[this.form.gymId?'put':'post'](`gym/${this.form.gymId?'update':'add'}`,this.form).then((res)=>{
                    this.dialogFormVisible = false;
                    this.getList(10,this.currentPage);
                }).catch((error)=>{
                    this.$notify.error({title: '错误',message:error||'保存失败！'});
                })
            },
            validateFun:function(){
                var errorInfo=[]; 
                this.$refs.form.validateField(['gymName', 'gymLocation', 'gymTelephone', 'gymServerAddress', 'gymExpireTime', 'gymDesc'],( re ) => {
                    if(re){
                        errorInfo.push(re);
                    }
                })
                return errorInfo.join(',');
            },
            pageSizeChange:function(val){
                this.pageSize = val;
                this.getList(val,this.currentPage);
            },
            pageCurrentChange:function(val){
                this.currentPage = val
                this.getList(this.pageSize,val);
            }
        }
    }
</script>
<style>
    
</style>